import config from "../../configGame/configGame"

var plugin = requirePlugin("task");
var memberPlugin = requirePlugin("cemMember");

Page({
  data: {

    imgData: {},
    isScroll: true,    //页面是否可以滚动   ******************************
    isShowList: false,  //是否显示排行榜
    isShowRules: false, //是否显示规则弹窗
    isShowTask: false,  //是否显示任务弹窗  
    isShowPrize: false,   //奖品
    isShowCollection:false,   //收藏弹窗
    isShowMatching:false,
    isShowGameResultPopLoser:false,  //是否显示游戏失败结果弹窗
		isShowGameResultPopVictory:false, //是否显示游戏胜利结果弹窗
		isShowTip:false,				//是否显示游戏次数不足弹窗
		isShowTimeOut:false,
    matchingLen:1,
    index: 0,
    flag: true,
    drawsNum:0,     //剩余游戏次数
 
    navBar: [
      {
        url:"https://img.alicdn.com/imgextra/i3/4161056916/O1CN010IgRNL20xZqkKcqOW_!!4161056916.jpg",
        width: "540",
        height: "540",
        index: 0,
        jumpLink: 1,
      },
      {
        url:"https://img.alicdn.com/imgextra/i3/4161056916/O1CN010IgRNL20xZqkKcqOW_!!4161056916.jpg",
        width: "540",
        height: "540",
        index: 1,
        jumpLink: 2,
      },
      {
        url:"https://img.alicdn.com/imgextra/i3/4161056916/O1CN010IgRNL20xZqkKcqOW_!!4161056916.jpg",
        width: "540",
        height: "540",
        index: 2,
        jumpLink: 3,
      }
    ],
    // 切换按钮
    switchBtn: {
      url:"https://img.alicdn.com/imgextra/i1/4161056916/O1CN01eiTdgB20xZqgZe6de_!!4161056916.png",
      width: 47,
      heihgt: 77,
    },
    switchBtn1: {
      url: 'https://img.alicdn.com/imgextra/i3/4161056916/O1CN01OGvo3X20xZqdgBm7u_!!4161056916.png',
      width: 47,
      heihgt: 77,
    },
    roomId:'',              //房间号码
    showGame:'main',          //显示游戏  ***********************************  game -- matching -- main
    difficulty:'easily',    //游戏难度
    activeIdx:6,            //拼图碎片数量
    startGame:false,        //是否开始了匹配状态，避免多次匹配

    mineData:{},
    enemyData:{},
    numberOne:[],       //第一名
    contenWidth:500,
    contenPosi:"48,20",
    listData:[],      //排行榜数据
    userInfo:'',      //当前用户排名
    // grade:[              //等级 ********************* 以废弃
    //   {
    //     url:'https://img.alicdn.com/imgextra/i4/4161056916/O1CN01nrwxKh20xZqbAgFqk_!!4161056916.png',
    //     text:'低'
    //   },
    //   {
    //     url:'https://img.alicdn.com/imgextra/i4/4161056916/O1CN01nrwxKh20xZqbAgFqk_!!4161056916.png',
    //     text:'中'
    //   },
    //   {
    //     url:'https://img.alicdn.com/imgextra/i4/4161056916/O1CN01nrwxKh20xZqbAgFqk_!!4161056916.png',
    //     text:'高'
    //   }
    // ],
    // collectionBtn:[
    //   {
    //     url:'https://img.alicdn.com/imgextra/i3/4161056916/O1CN019uDzUs20xZqfxLNxO_!!4161056916.png'
    //   },
    //   {
    //     url:'https://img.alicdn.com/imgextra/i1/4161056916/O1CN01K3jUbe20xZqiB3c8o_!!4161056916.png'
    //   }
    // ],     //收藏按钮
    goods:[

    ],    //商品信息
    popData:'',       //游戏结束后的弹窗
    rules:'',       //规则
    bigPrize:'',      //大奖
		shareData:'',      //自定义分享信息


		//活动是否结束
		timeDownIs:false,
		

		//任务按钮组
    taskBtns:[],
		// jifen:{
    //     bgimg:"https://img.alicdn.com/imgextra/i2/4161056916/O1CN01fRQTAV20xZqmr1DjX_!!4161056916.png",
    //     btnH:'https://img.alicdn.com/imgextra/i1/4161056916/O1CN01ovRHDk20xZqdvYEu8_!!4161056916.png',
    //     btn:"https://img.alicdn.com/imgextra/i1/4161056916/O1CN011YlTxn20xZqcNB5qb_!!4161056916.png",
    //     type:"jifen",
    //     name:"积分兑换"
    // },

    overTaskBtns:"https://img.alicdn.com/imgextra/i2/4161056916/O1CN01bhkmNX20xZqdE9is5_!!4161056916.png",     //完成按钮
    TaskStatus:'',     //今日完成状态
		prize:'',
		

		activityInfo:'',

		currentIndex:0,


		//资源*******************

		//背景图
		// bg:{
		// 	url:'https://img.alicdn.com/imgextra/i3/4161056916/O1CN01wnmh0Z20xZqnJbld8_!!4161056916.jpg',
		// 	width:750,
		// 	height:1624
		// },


		//按钮组
		// btns:{
		// 	list:{
		// 		url:'https://img.alicdn.com/imgextra/i4/4161056916/O1CN01dgPukh20xZqfbbvhW_!!4161056916.png',
		// 		width:112,
		// 		height:122
		// 	},
		// 	rule:{
		// 		url:'https://img.alicdn.com/imgextra/i2/4161056916/O1CN01p6HVfu20xZqmeIf1e_!!4161056916.png',
		// 		width:112,
		// 		height:122
		// 	},
		// 	task:{
		// 		url:'https://img.alicdn.com/imgextra/i1/4161056916/O1CN01AiEyfx20xZqkdRibi_!!4161056916.png',
		// 		width:112,
		// 		height:122
		// 	},
		// 	prize:{
		// 		url:'https://img.alicdn.com/imgextra/i4/4161056916/O1CN01rcJtBI20xZqiXUROb_!!4161056916.png',
		// 		width:112,
		// 		height:122
		// 	},
		// },

		//小红心
		// head:{
		// 	url:'https://img.alicdn.com/imgextra/i2/4161056916/O1CN013QALv120xZqnXKdKy_!!4161056916.png',
		// 	width:44,
		// 	height:41
		// },

		//背景板
		// bgBan:{
		// 	url:'https://img.alicdn.com/imgextra/i1/4161056916/O1CN01tweasB20xZqkhdK4v_!!4161056916.png',
		// 	width:700,
		// 	height:1030
		// },

		//开始游戏按钮
		// startBtn:{
		// 	invitation:{
		// 		url:'https://img.alicdn.com/imgextra/i1/4161056916/O1CN015gRjGx20xZqiXqfAe_!!4161056916.png',
		// 		width:248,
		// 		height:84
		// 	},
		// 	start:{
		// 		url:'https://img.alicdn.com/imgextra/i4/4161056916/O1CN01yrS4VL20xZqfbvCHG_!!4161056916.png',
		// 		width:248,
		// 		height:84
		// 	}
		// },

		//难度按钮组
		// difficultyBtns:[
		// 	{
		// 		url:'https://img.alicdn.com/imgextra/i4/4161056916/O1CN01Dqbm4h20xZqhq8qWl_!!4161056916.png',
		// 		width:296,
		// 		height:140
		// 	},
		// 	{
		// 		url:'https://img.alicdn.com/imgextra/i4/4161056916/O1CN01UsQAAt20xZqhaAjwA_!!4161056916.png',
		// 		width:296,
		// 		height:140
		// 	},
		// 	{
		// 		url:'https://img.alicdn.com/imgextra/i3/4161056916/O1CN01OvErWK20xZqioPcWz_!!4161056916.png',
		// 		width:296,
		// 		height:140
		// 	}
		// ],

		liu:{
			is:false,
			count:0,
			total:0,
			type:'VIEW_STORE'
		},
		zhi:{
			is:false,
			count:0,
			total:0,
			type:'LIVE'
		},

  },

  //检测会员
  TestingMembers(){

    let this_ = this

    //this.openMember();

    memberPlugin.checkMember({
      
      //sellerId为可选参数，不填则为当前小程序Owner用户ID

      sellerId:2838892713,

      success(v) {
        
        // my.alert({
        //   title: "会员检查成功",
        //   content: v.data.isMember,
        // })  

        if( v.data.isMember == false || v.data.isMember == 'false' ){ 
          
          this_.openMember();

        }
        // else{

        //   my.alert({
        //     title: "已入会",
        //     content: v.data.isMember,
        //   }) 
        // }


      },
      fail(v) {
        // my.alert({
        //   title: "会员检查失败",
        //   content: JSON.stringify(v),
        // })          
      }      
    });

  },

  async openMember() {   
    this.setData({
      expend:true
    })
  },

  async onClose(event) {

    // my.alert({
    //   title: "入会弹窗点击关闭后回调",
    //   content: event,
    // })  
    
    this.setData({
      expend:false,
    })

  },

  //入会成功的回调
  async onAuthSuccess(res) {

    // my.alert({
    //   title: "入会成功的回调",
    //   content: res,
    // })  

    this.setData({
      expend:false
    })

    this.joinVip();

  },

  //入会失败的回调
  async onAuthFail(res) {

    // my.alert({
    //   title: "入会失败的回调",
    //   content: JSON.stringify(res),
    // })  

    this.setData({
      expend:false,
    })

    

  },



  // 切换会场*****************
  switchNavBarFn(direction) {
    let arr;
    let obj = {
      pev: () => {
        this.index = this.index >= 2 ? 0 : this.index + 1;
        arr = this.data.navBar.map((v) => {

          return {
            ...v,
            index: v.index >= 2 ? 0 : v.index + 1,
          };
        });
      },

      next: () => {
        this.index = this.index <= 0 ? 2 : this.index - 1;
        arr = this.data.navBar.map((v) => {
          return {
            ...v,
            index: v.index <= 0 ? 2 : v.index - 1,
          };
        });
      },
		};
		

		obj[direction]();

		// console.info(this.data.currentIndex)
		
		// console.info(arr)
    this.setData({
			navBar: arr
    });
    arr = null;
  },

  

  // 切换按钮
  changeFn(e) {
    // if (!this.flag) return
    this.flag = false
    const { status } = e.currentTarget.dataset;
    let index
    if (status == 'next') {
      index = this.data.currentIndex >= 2 ? 0 : this.data.currentIndex + 1
    }
    else {
      index = this.data.currentIndex <= 0 ? 2 : this.data.currentIndex - 1
    }
    this.setData({
      currentIndex: index,
    })
    setTimeout(() => {
      this.flag = true
    }, 500);
    this.switchNavBarFn(status);

  },

  // 轮播改变 
  swiperChange(e) {

    let place = [[0, 1, 2], [2, 0, 1], [1, 2, 0]]

    let arr = this.data.navBar.map((v, i) => {
      return {
        ...v,
        index: place[e.detail.current][i],
      };
    });

    this.setData({
      currentIndex: e.detail.current,
      navBar: arr
    })


  },

	//************************************
	
	complete(item) {

		let { value = {} } = item.target.dataset   

		console.info(value.total)
		console.info(parseInt(value.awardConfig))
		plugin.triggerItem(value)
		.then(res => {
			console.log('res',res)

			if(value.type == 'SIGN'){

        this.sign();
        
			}else if(value.type == 'views'){

				this.setData({
					liu:{
							is:true,
							count:value.count,
							total:value.total,
							prizeNum:parseInt(value.awardConfig),
							type:'VIEW_STORE'
					}
				})
			}else if(value.type == 'view'){
				this.setData({
					zhi:{
							is:true,
							count:value.count,
							total:value.total,
							prizeNum:parseInt(value.awardConfig),
							type:'LIVE'
					}
				})
			}

		}).catch(err => {
			console.log('err', err)
		})
	},

	//浏览店铺
	seeDian(o){
		getApp().cloud.application.httpRequest({
      'path' : '/api/c/task/viewStore', 
      'method':'POST',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
      'body':{
				type:'VIEW_STORE',
				"dayLimit": o.total,
  			"gameTime": parseInt(o.awardConfig)
			},
      'exts':{}  }).then(res => {

      console.log("浏览店铺",res);

      //判断是否是正常状态
      if(res.code != 200){
        // my.alert({
        //   content:res.msg
        // }) 
      }else{
        // my.alert({
        //   content:"签到成功！"
				// })
				this.changePage();

				this.showToast({content:'浏览成功'})
				
				setTimeout(() => {
					this.showTask();
				}, 200);

        // 埋点
        getApp().BuriedPoint({actionText:"浏览店铺",actionType:"viewStore"})
      }
    })
	},

	//观看直播
	seeZhi(o){
		getApp().cloud.application.httpRequest({
      'path' : '/api/c/task/live', 
      'method':'POST',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
      'body':{
				type:"LIVE",
				"dayLimit": o.total,
  			"gameTime": parseInt(o.awardConfig),
			},
      'exts':{}  }).then(res => {

      console.log("观看直播",res);

      //判断是否是正常状态
      if(res.code != 200){
        // my.alert({
        //   content:res.msg
        // }) 
      }else{
        // my.alert({
        //   content:"签到成功！"
				// })
				this.changePage();

				this.showToast({content:'观看直播任务完成'})
				
				setTimeout(() => {
					this.showTask();
				}, 200);

        // 埋点
        getApp().BuriedPoint({actionText:"观看直播任务完成",actionType:"seeZhiBo"})
      }
    })
	},

  //今日完成任务状态
  getTodayTaskStatus(){
    getApp().cloud.application.httpRequest({
      'path' : '/api/c/task/taskCompleteStatus', 
      'method':'GET',
      'headers':{ "Content-Type":"application/json"},
      'params':{  },
      'body':{  },
      'exts':{}  }).then(res => {

        console.log("今日完成任务状态",res);
        //判断是否是正常状态
        if(res.code != 200){
          my.alert({
            content:res.msg
          }) 
        }else{
				
          let aa = getApp().pifu.indexPage.taskBgBtns

          aa = JSON.parse(JSON.stringify(aa));

          let arr = []

          let huan = JSON.parse(JSON.stringify(res.data));
          
					for(let i in huan){
						if(huan[i].type == 'SIGN'){
							huan.splice(i,1)
						}
					}

					let lin = []

					plugin.getTaskList().then(result => {

						let taskData = JSON.parse(JSON.stringify(result))
           
						taskData.map((v,i) => {
							
							v.count=v.finishCount,
							v.orderIndex=i,
							v.title=v.taskTitle,
							v.total=v.taskCount,
							v.type=v.actionType == 'EXCUTE' ? v.taskTitle == '浏览直播15S' ? 'view' : 'views' : v.actionType
							v.gameTime = parseInt(v.awardConfig)

              //view -- 直播      views -- 店铺
							if(v.actionType == 'EXCUTE' && v.taskTitle == '浏览直播15S' && this.data.zhi.is){
								if(v.finishCount > this.data.zhi.count){
									this.seeZhi(v)
								}

								this.setData({
									zhi:{
										is:false,
										count:0,
										total:0,
										type:'LIVE'
									}
								})
              }
              
        
							if(v.actionType == 'EXCUTE' && v.taskTitle != '浏览直播15S' && this.data.liu.is){
								if(v.finishCount > this.data.liu.count){
									this.seeDian(v)
								}

								this.setData({
									liu:{
										is:false,
										count:0,
										total:0,
										type:'VIEW_STORE'
									}
								})
              }
              
              huan.unshift(v)
              
            })

            
            

							aa.map((v,i) => {
                console.info(v)
								huan.map((x,y) => {
									if(v.type == x.type){
										arr.push(v)
									}
								})
							})

							this.setData({
								TaskStatus:huan,
								taskBtns:arr
							})


						// console.info('=========================>',huan)
            console.info('==========arr===============>',arr)
            
					}).catch(err => {
            console.info(err)
					})


          
        }
    })
  },

  //用来刷新签到的
  getTodayTaskStatus1(){
    getApp().cloud.application.httpRequest({
      'path' : '/api/c/task/taskCompleteStatus', 
      'method':'GET',
      'headers':{ "Content-Type":"application/json"},
      'params':{  },
      'body':{  },
      'exts':{}  }).then(res => {

        console.log("今日完成任务状态",res);
        //判断是否是正常状态
        if(res.code != 200){
          my.alert({
            content:res.msg
          }) 
        }else{

          //任务按钮皮肤
          let aa = getApp().pifu.indexPage.taskBgBtns

          aa = JSON.parse(JSON.stringify(aa));

          let arr = []

          let huan = JSON.parse(JSON.stringify(res.data));
          
					for(let i in huan){
						if(huan[i].type == 'SIGN'){
							huan.splice(i,1)
						}
					}

					let lin = []

					plugin.getTaskList().then(result => {

						let taskData = JSON.parse(JSON.stringify(result))
           
						taskData.map((v,i) => {
							
							v.count=v.finishCount,
							v.orderIndex=i,
							v.title=v.taskTitle,
							v.total=v.taskCount,
							v.type=v.actionType == 'EXCUTE' ? v.taskTitle == '浏览直播15S' ? 'view' : 'views' : v.actionType
							v.gameTime = parseInt(v.awardConfig)

              //view -- 直播      views -- 店铺
							if(v.actionType == 'EXCUTE' && v.taskTitle == '浏览直播15S' && this.data.zhi.is){
								if(v.finishCount > this.data.zhi.count){
									this.seeZhi(v)
								}

								this.setData({
									zhi:{
										is:false,
										count:0,
										total:0,
										type:'LIVE'
									}
								})
              }
              
        
							if(v.actionType == 'EXCUTE' && v.taskTitle != '浏览直播15S' && this.data.liu.is){
								if(v.finishCount > this.data.liu.count){
									this.seeDian(v)
								}

								this.setData({
									liu:{
										is:false,
										count:0,
										total:0,
										type:'VIEW_STORE'
									}
								})
              }
              
              huan.unshift(v)
              
            })


            taskData.map((val)=>{
              if(val.type == 'SIGN'){
                  val.count=1,
                  val.total=1
              }
            })

							aa.map((v,i) => {
                console.info(v)
								huan.map((x,y) => {
									if(v.type == x.type){
										arr.push(v)
									}
								})
							})

							this.setData({
								TaskStatus:huan,
								taskBtns:arr
							})


						// console.info('=========================>',huan)
            console.info('==========arr===============>',arr)
            
					}).catch(err => {
            console.info(err)
					})


          
        }
    })
	},
	
  //获取自定义分享信息
  getShare(){
    getApp().cloud.application.httpRequest({
      'path' : '/api/c/task/getShareContent', 
      'method':'GET',
      'headers':{ "Content-Type":"application/json"},
      'params':{  },
      'body':{  },
      'exts':{}  }).then(res => {

        console.log("自定义分享信息",res);
        //判断是否是正常状态
        if(res.code != 200){
          // my.alert({
          //   content:res.msg
          // }) 
        }else{
          this.setData({
            shareData:res.data
          })
        }
    })
  },

  // 大奖
  getBigPrize(){
    getApp().cloud.application.httpRequest({
      'path' : '/api/c/prize/getFirstPrize', 
      'method':'GET',
      'headers':{ "Content-Type":"application/json"},
      'params':{  },
      'body':{  },
      'exts':{}  }).then(res => {

        console.log("大奖",res);
        //判断是否是正常状态
        if(res.code != 200){r
          // my.alert({
          //   content:res.msg
          // }) 
        }else{
          this.setData({
            bigPrize:res.data.prizeName
          })
        }
    })
  },

  //规则
  getRules(){

    getApp().cloud.application.httpRequest({
      'path' : '/api/c/user/getRuleText', 
      'method':'POST',
      'headers':{ "Content-Type":"application/json"},
      'params':{  },
      'body':{  },
      'exts':{}  }).then(res => {

				console.log("规则",res.data.split('[回车]'));

        //判断是否是正常状态
        if(res.code != 200){
          // my.alert({
          //   content:res.msg
          // }) 
        }else{
          this.setData({
            rules:res.data.split('[回车]')
          })
        }
    })
  },

  // 获取收藏商品组
  getCollection(){
    getApp().cloud.application.httpRequest({
      'path' : '/api/c/task/getCollectProduct', 
      'method':'GET',
      'headers':{ "Content-Type":"application/json"},
      'params':{  },
      'body':{  },
      'exts':{}  }).then(res => {

        console.log("获取收藏商品组",res);

        //判断是否是正常状态
        if(res.code != 200){
          // my.alert({
          //   content:res.msg
          // }) 
        }else{

          this.setData({
            goods:res.data
					})

          //this.goodss.status(res.data)

        }
    })
  },

  // 获取排行榜第一名
  geiNumberOne(){
    getApp().cloud.application.httpRequest({
      'path' : '/api/c/user/rankingList', 
      'method':'POST',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
      'body':{ type:2 },
      'exts':{}  }).then(res => {

        console.log("获取排行榜第一名",res);

        //判断是否是正常状态
        if(res.code != 200){
          // my.alert({
          //   content:res.msg
          // }) 
        }else{
          // let newArr=[res.data]
          // this.setData({
          //   numberOne:newArr.concat(newArr)
          // })
          // console.log(this.data.numberOne)
          this.setData({
            numberOne:res.data
          })
        }
    })
  },

  //获取奖品信息
  getPrize(){
    getApp().cloud.application.httpRequest({
      'path' : '/api/c/prize/myPrize', 
      'method':'GET',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
      'body':{},
      'exts':{}  }).then(res => {

        console.log("获取奖品信息",res);

        //判断是否是正常状态
        if(res.code != 200){
          // my.alert({
          //   content:res.msg
          // }) 
        }else{
          this.setData({
            prize:res.data
          })
        }
    })
  },

  // 获取游戏次数
  getGameNum(){
    getApp().cloud.application.httpRequest({
      'path' : '/api/c/user/currentUserInfo', 
      'method':'POST',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
      'body':{},
      'exts':{}  }).then(res => {

      console.log("获取用户信息",res);

      //判断是否是正常状态
      if(res.code != 200){
        // my.alert({
        //   content:res.msg
        // }) 
      }else{
        this.setData({
          drawsNum:res.data.gameTime
        })
      }
    })
  },

  //获取排行榜数据
  getList(){
    getApp().cloud.application.httpRequest({
      'path' : '/api/c/user/rankingList', 
      'method':'POST',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
      'body':{},
      'exts':{}  }).then(res => {

      console.log("获取排行榜数据",res);

      //判断是否是正常状态
      if(res.code != 200){
        // my.alert({
        //   content:res.msg
        // }) 
      }else{
        this.setData({
          listData:res.data
        })
      }
    })
  },


  //当前用户排名
  getUserInfo(){
    getApp().cloud.application.httpRequest({
      'path' : '/api/c/user/myRankingVo', 
      'method':'POST',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
      'body':{},
      'exts':{}  }).then(res => {

      console.log("当前用户排名",res);

      //判断是否是正常状态
      if(res.code != 200){
        // my.alert({
        //   content:res.msg
        // }) 
      }else{

				let mineData = this.data.mineData;

				mineData.ranking = res.data.rankingIndex

        this.setData({
					userInfo:res.data,
					mineData:mineData
        })
      }
    })
  },

  // 排行榜
  showList() {

    this.setData({
      isScroll: true,
      isShowList: true
		})
		
		console.info(this.data.userInfo)

		setTimeout(() => {
			this.listPage.setData({
				userInfo:this.data.userInfo
			})
		}, 100);

		// this.listPage.upDateList(this.data.userInfo)
		


  },

  // 规则
  showRules() {

    this.setData({
      isScroll: true,
      isShowRules: true
    })

  },

  // 任务
  showTask() {

    this.setData({
      isScroll: true,
      isShowTask: true
    })
    
    setTimeout(() => {

      this.msgg.msg(this.data.TaskStatus)

    }, 200);

  },

  // 奖品
  showPrize(){

		this.changePage()

    

		clearTimeout(this.prizzeSetLin)
		
		this.prizzeSetLin = setTimeout(() => {

			this.setData({
				isShowPrize: true
			})


			this.prizePage.prize(this.data.prize)
		}, 100);

  },



  // 签到
  sign() {

		let that = this
    getApp().cloud.application.httpRequest({
      'path' : '/api/c/task/sign', 
      'method':'POST',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
      'body':{},
      'exts':{}  }).then(res => {

      //console.log("签到",res);

      //判断是否是正常状态

      if(res.code != 200){
        // my.alert({
        //   content:res.msg
        // }) 
      }else{

        my.showToast({
          content:"签到成功！"
        })
        
        that.changePage();
        
        that.getTodayTaskStatus1();
				
				setTimeout(() => {
					that.showTask();
				}, 600);

        // 埋点
        getApp().BuriedPoint({actionText:"签到",actionType:"sign"})
      }
    })

  },

  //获取关注店铺id
  getShopId(){
		
    getApp().cloud.application.httpRequest({
      'path' : '/api/c/task/sellerGet', 
      'method':'GET',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
      'body':{},
      'exts':{}  }).then(res => {

      console.log("店铺信息======>",res);

      //判断是否是正常状态
      if(res.code != 200){
        // my.alert({
        //   content:res.msg
        // }) 
      }else{

        //关注过后的用户每日增加次数
        my.tb.checkShopFavoredStatus({
          id: Number(res.data.sid),
          success: (ress) => {
            // my.alert({ content: ress })
            if(ress.isFavor){
              getApp().cloud.application.httpRequest({
              'path' : '/api/c/user/addDayGameTimeForFollow', 
              'method':'POST',
              'headers':{ "Content-Type":"application/json"},
              'params':{},
              'body':{},
              'exts':{}  }).then(res => {
                if(res.code != 200){
                  // my.alert({
                  //   content:res.msg
                  // }) 
                }else{
                  // my.alert({
                  //   content:"关注用户每日进入增加机会"
                  // })
                  this.changePage();
                  // 埋点
                  getApp().BuriedPoint({actionText:"关注",actionType:"follow"})
                }
              })
            }

          },
          fail: (res) => {

            //my.alert({ content: "fail" })
          }
        })

        this.setData({
          shopId:res.data.sid
        })
        
      }
    })
  },

  // 关注
  favorShop() {
    getApp().cloud.application.httpRequest({
      'path' : '/api/c/task/sellerGet', 
      'method':'GET',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
			'body':{},
      'exts':{}  }).then(result => {

				console.info(result)
				// console.info(typeof(parseInt(res.data.sid)))

				my.tb.checkShopFavoredStatus({
						id: parseInt(result.data.sid),
						success: (reacv) => {
								// my.alert({ content: "success" })

								console.info(reacv)

								if(reacv.isFavor){
									getApp().cloud.application.httpRequest({
										'path' : '/api/c/task/notice', 
										'method':'POST',
										'headers':{ "Content-Type":"application/json"},
										'params':{},
										'body':{},
										'exts':{}  }).then(res => {

										console.log("关注",res);

										//判断是否是正常状态
										if(res.code != 200){
											// my.alert({
											//   content:res.msg
											// }) 
										}else{
											my.showToast({
												content:"关注成功"
											})
											this.changePage();

											setTimeout(() => {
												this.showTask();
											}, 400);
											
										}
									})
								}else{
									my.tb.favorShop({
										id: parseInt(result.data.sid),
										success: () => {
											// my.alert({ content: "关注成功" })

											getApp().cloud.application.httpRequest({
												'path' : '/api/c/task/notice', 
												'method':'POST',
												'headers':{ "Content-Type":"application/json"},
												'params':{},
												'body':{},
												'exts':{}  }).then(res => {

												console.log("关注",res);

												//判断是否是正常状态
												if(res.code != 200){
													// my.alert({
													//   content:res.msg
													// }) 
												}else{
													my.showToast({
														content:"关注成功"
													})
													this.changePage();

													setTimeout(() => {
														this.showTask();
													}, 400);
													
												}
											})

										},
										fail: (res) => {
											console.info(res)
										}
									})
								}
						},
						fail: (res) => {
								my.alert({ content: "fail" })
						}
				})


				
			})



    

  },

  // 加入会员
  joinMember() {

		getApp().cloud.application.httpRequest({
				
				'path' : '/api/c/user/getStoreInfo', 
				'method':'get',
				'headers':{ "Content-Type":"application/json"},
				'params':{},
				'body':{},
			
			'exts':{}  }).then(res => {
				console.info('入会======================》',res)

				if(res.code != 200){

					my.showToast({content:res.msg});

					return
				}


				my.call('navigateToOutside',{
					url:
						// 'https://market.m.taobao.com/app/sj/member-center-rax/pages/pages_index_index?wh_weex=true&sellerId=3256243055&extraInfo=%7B%22source%22%3A%22isvapp%22%2C%22activityId%22%3A%2212345677%22%2C%22entrance%22%3A%22hudong%22%7D&callbackUrl=https%3A%2F%2Fm.duanqu.com%3F_ariver_appid%3D3000000027123154%26page%3Dpages%2Ftask%2Ftask'
						// 'https://market.m.taobao.com/app/sj/member-center-rax/pages/pages_index_index?wh_weex=true&sellerId='+ 2207927654285 +'&extraInfo=%7B%22source%22%3A%22isvapp%22%2C%22activityId%22%3A%2212345677%22%2C%22entrance%22%3A%22hudong%22%7D&callbackUrl=https%3A%2F%2Fm.duanqu.com%3F_ariver_appid%3D'+ res.data.app_id +'%26page%3Dpages%2Fload%2Fload'
						'https://market.m.taobao.com/app/sj/member-center-rax/pages/pages_index_index?wh_weex=true&sellerId='+ res.data.store_id +'&extraInfo=%7B%22source%22%3A%22isvapp%22%2C%22activityId%22%3A%2212345677%22%2C%22entrance%22%3A%22hudong%22%7D&callbackUrl=https%3A%2F%2Fm.duanqu.com%3F_ariver_appid%3D'+ res.data.app_id +'%26page%3Dpages%2Fload%2Fload'
					},(res)=>{ 
        })
        

			})

    

  },


  // 加入会员接口
  joinVip(){
    getApp().cloud.application.httpRequest({
      'path' : '/api/c/task/member', 
      'method':'POST',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
      'body':{},
      'exts':{}  }).then(res => {

      console.log("加入会员",res);

      // my.alert({
      //   title:"加入会员",
      //   content:JSON.stringify(res.data)
      // }) 

      //判断是否是正常状态
      if(res.code != 200){

        // my.alert({
        //   content:res.msg
        // }) 

      }else{
        // my.alert({
        //   content:"加入会员成功！"
        // })

        this.changePage();
        //埋点
        getApp().BuriedPoint({actionText:"入会",actionType:"membership"})
      }
    })
  },

  
  // 跳转收藏页
  collectGoods() {
    //my.alert({ content: "收藏" })
    //my.navigateTo({ url: '../goods/goods' })
    this.setData({
      isScroll: true,
      isShowCollection: true
		})

		this.getCollection();
		

		
		setTimeout(() => {
			this.collectionPage.setData({
				goods:this.data.goods
			})

			setTimeout(() => {
				this.collectionPage.isCollect()
			}, 100);
		}, 300);

  },

  // 点击收藏
  collection(e){

    console.log(e);
    // return
    my.tb.collectGoods({
      id: parseInt(e),
      success: (res) => {
        
        getApp().cloud.application.httpRequest({
          'path' : '/api/c/task/collect', 
          'method':'POST',
          'headers':{ "Content-Type":"application/json"},
          'params':{},
          'body':{productId:e},
          'exts':{}  }).then(res => {

            console.log("点击收藏",res);

            //判断是否是正常状态
          if(res.code != 200){
            my.showToast({
              content:res.msg
						}) 
						
						console.info(res)

            //取消收藏
            my.tb.unCollectGoods({
              id: parseInt(e),
              success: (res) => {
                
              },
              fail: (res) => {
                
              },
              complete: (res) => {
                
              }
            })

          }else{

            my.showToast({
              content:"收藏成功"
						})
						
						this.collectGoods()
            
          }
        })

				this.changePage();
				setTimeout(() => {
					this.showTask();
				}, 200);
        //埋点
        getApp().BuriedPoint({actionText:"收藏商品",actionType:"collectProduct"})
        
        
      },
      fail: (res) => {
        // my.alert({ content: "收藏失败" })
      },
      complete: (res) => {
        //my.alert({ content: "complete - " + JSON.stringify(res) })
      }
    })
  },

  // 分享
  share() {

    my.showSharePanel();

    this.setData({
      roomId:'biaoji'
		})
		
		getApp().BuriedPoint({actionText:"分享",actionType:"share"})

  },

  //打开收货地址
  gress(){
    my.authorize({
      scopes: 'scope.addressList',
      success: (res) => {
        my.tb.chooseAddress({
          addAddress: "show",
          searchAddress: "show",
          locateAddress: "show"
        }, (res) => {
          // my.alert({ content: "success - " + JSON.stringify(res) })

					// console.info(res)
					console.info('领奖ID=========》',this.data.userInfo)

          getApp().cloud.application.httpRequest({
            'path' : '/api/c/prize/address', 
            'method':'POST',
            'headers':{ "Content-Type":"application/json"},
            'params':{},
            'body':{
                    id:this.data.userInfo.prizeLog.id,
                    phone:res.telNumber,
                    receiverAddress:res.detailInfo,
                    receiverArea: res.countyName,
                    receiverCity: res.cityName,
                    receiverProvince:res.provinceName
                  },
            'exts':{}  }).then(res => {

            console.log("用户领取奖品地址=====>",res);

            //判断是否是正常状态
            if(res.code != 200){
              // my.alert({
              //   content:res.msg
              // }) 
            }else{
              
            }
          })

        })
      },
    });
    

	},
	
	gressNew(id){

			my.tb.confirmCustomOrder({
				data:{
					'itemId':parseInt(id),
					'quantity':1
				},
				success:function(e) {   },
				// fail:function(e) {  my.alert({  title: 'fail ',  content: JSON.stringify(e)  })  }  
			});

		// my.authorize({
    //   scopes: 'scope.addressList',
    //   success: (res) => {
    //     my.tb.chooseAddress({
    //       addAddress: "show",
    //       searchAddress: "show",
    //       locateAddress: "show"
    //     }, (res) => {
		// 			console.info(res)

    //       getApp().cloud.application.httpRequest({
    //         'path' : '/api/c/prize/topPrizeReceive', 
    //         'method':'POST',
    //         'headers':{ "Content-Type":"application/json"},
    //         'params':{},
    //         'body':{
    //                 phone:res.telNumber,
    //                 receiverAddress:res.detailInfo,
    //                 receiverArea: res.countyName,
    //                 receiverCity: res.cityName,
    //                 receiverProvince:res.provinceName
    //               },
    //         'exts':{}  }).then(result => {

		// 					console.info('================',result)

    //         //判断是否是正常状态
    //         if(result.code != 200){
    //           my.alert({
    //             content:res.msg
    //           }) 
    //         }else{
    //           my.showToast({
		// 						content:'领取成功'
		// 					})
    //         }
    //       })

    //     })
    //   },
    // });
	},

  //浏览种草商品
  viewProduct(diff){
    
    getApp().cloud.application.httpRequest({
      'path' : '/api/c/task/viewProduct', 
      'method':'POST',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
      'body':{
				level:diff
			},
      'exts':{}  }).then(res => {

      console.log("浏览种草商品",res);

      //判断是否是正常状态
      if(res.code != 200){

        // my.alert({
        //   content:res.msg
        // }) 

      }else{
        my.showToast({
          content:"获得游戏次数"
        })

        //埋点
        getApp().BuriedPoint({actionText:"浏览商品",actionType:"browseProduct"})

      }
    })

	},
	
	//获取活动信息
	getActivityInfo(){
		getApp().cloud.application.httpRequest({
      'path' : '/api/c/user/currentActivityInfo', 
      'method':'POST',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
      'body':{
        "gameLogId": this.data.roomId
      },
      'exts':{}  }).then(res => {

      console.log("获取活动信息====》",res);

      //判断是否是正常状态
      if(res.code != 200){

        my.showToast({
          content:res.msg
        }) 

      }else{
        
				// console.info('获取活动信息===>',res)

				// {
				// 	url:"https://img.alicdn.com/imgextra/i4/4161056916/O1CN01kBtL8V20xZqh3zxM8_!!4161056916.png",
				// 	width: "580",
				// 	height: "580",
				// 	index: 0,
				// 	jumpLink: 1,
				// }

				let levelInfo = res.data.levelInfoList;

				let nav = this.data.navBar;

				let difImg=[]

				let difficultyBtns=[
					{
						url:'https://img.alicdn.com/imgextra/i4/4161056916/O1CN01Dqbm4h20xZqhq8qWl_!!4161056916.png',
						width:296,
						height:140
					},
					{
						url:'https://img.alicdn.com/imgextra/i4/4161056916/O1CN01UsQAAt20xZqhaAjwA_!!4161056916.png',
						width:296,
						height:140
					},
					{
						url:'https://img.alicdn.com/imgextra/i3/4161056916/O1CN01OvErWK20xZqioPcWz_!!4161056916.png',
						width:296,
						height:140
					}
				]

				if(levelInfo.length == 1){
					nav.map((v,i) => {
						v.url = levelInfo[0].pictureUrl
						v.diff = levelInfo[0].difficulty
						v.winScore = levelInfo[i].winScore
						v.gameTime = levelInfo[0].gameTime

						difImg.push(difficultyBtns[levelInfo[0].difficulty - 1])
					})
				}else if(levelInfo.length == 2){
					nav.map((v,i) => {
						if((i + 1)%2 != 0){
							v.url = levelInfo[0].pictureUrl
							v.diff = levelInfo[0].difficulty
							v.winScore = levelInfo[0].winScore
							v.gameTime = levelInfo[0].gameTime

							difImg.push(difficultyBtns[levelInfo[0].difficulty - 1])
						}else{
							v.url = levelInfo[1].pictureUrl
							v.diff = levelInfo[1].difficulty
							v.winScore = levelInfo[1].winScore
							v.gameTime = levelInfo[1].gameTime

							difImg.push(difficultyBtns[levelInfo[1].difficulty - 1])
						}
					})
				}else{
					nav.map((v,i) => {
						v.url = levelInfo[i].pictureUrl
						v.diff = levelInfo[i].difficulty
						v.winScore = levelInfo[i].winScore
						v.gameTime = levelInfo[i].gameTime

						difImg.push(difficultyBtns[levelInfo[i].difficulty - 1])
					})
				}

				this.setData({
					navBar:nav,
					activityInfo:res.data,
					difficultyBtns:difImg
				})

				console.info('处理过的图片===>',nav)




				my.getServerTime().then(time => {
					let end = res.data.activity.endTime + ":00"
					
					let chuo = new Date(end).getTime()

					if(time.time - chuo > 0){
						this.setData({
							timeDownIs:true
						})
					}else{
						this.setData({
							timeDownIs:false
						})
					}


				})



      }
    })
	},

	// 取消匹配
	cancelSet(){
		clearTimeout(this.addGameSet)
		clearTimeout(this.startGameSet)
		clearTimeout(this.yaoqingSanShiMiao)
	},

  //游戏结束查询结果
  checkGameSuccess(o){

    getApp().cloud.application.httpRequest({
      'path' : '/api/c/game/getPkResultVo', 
      'method':'POST',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
      'body':{
        "gameLogId": this.data.roomId
      },
      'exts':{}  }).then(res => {

			console.log("查询游戏结果====》",res);
			
			// my.alert({title:'查询游戏结果',content:JSON.stringify(res)})

      //判断是否是正常状态
      if(res.code != 200){

        // my.alert({
        //   content:res.msg
        // }) 

      }else{
        
        this.setData({
          startGame:false,
          showGame:'main',
          isShowGameResultPopLoser:o == 'l',
          isShowGameResultPopVictory:o == 'v',
					popData:res.data,
					roomId:''
        })

      }
    })

  },

  //scoket连接
  linkSocket(){

		// console.info('链接',getApp().openId)
		console.info('连接')
		

    if(!getApp().openId || getApp().openId == ''){

			console.info('openId=======>',getApp().openId)

			clearTimeout(this.restSetTout)
			
			// getApp().getUserInfo()
			// getApp().httptest()

      // my.showToast({content:'未登陆'});

      return;
		}

			console.info('有了openId=======>',getApp().openId)

			// this.unLinkSocket()

			//新的
			// let url = `wss://www.gzxim.com.cn/socket/game/${getApp().openId}`

			//旧的
			// let url = `ws://39.100.39.158/socket/game/${getApp().openId}`

			// my.alert({content:'连接socket'})

			my.connectSocket({ 
				url: `wss://pk.online.gzxim.com.cn/socket/game/${getApp().openId}`,
				data: {},
				header:{
					'content-type': 'application/json'
				},
				success:res => {
					console.info('连接状态=',res)
					clearTimeout(this.restSetTout)
					// my.alert({title:'socket',content:JSON.stringify(res)})
				},
				fail:err => {
					console.info('连接错误=',err)
					clearTimeout(this.restSetTout)
					// my.alert({title:'socket',content:JSON.stringify(err)})
				}
			});
			
			// console.info(`ws://39.100.39.158/socket/game/${getApp().openId}`)

			my.onSocketError(err => {
				// console.info(err)
			});

			my.onSocketClose(res => {
				// console.info(res)
			})

			my.onSocketOpen(res => {
				console.log('WebSocket 连接已打开');

				// my.alert({content:'WebSocket 连接已打开'})
			});


			//socket通讯
			my.onSocketMessage((res) => {
				this.socketMsg(res.data)
			})


    

	},
	
	//心跳包 -- socket 重连机制
	resetLinkSocket(){


			this.restSocketSet = setInterval(() => {
				
				// console.info('心跳')
				
				// my.alert({content:'心跳'})

				my.sendSocketMessage({
					data: "你还活着吗？朋友", // 需要发送的内容
					success: (res) => {
						// console.info('启用延迟重连')


						// clearTimeout(this.restSetTout)

						// this.restSetTout = setTimeout(() => {
						// 	console.info('重连')
						// 	this.linkSocket()
						// }, 50);
					},
					fail:err => {
						clearTimeout(this.restSetTout)
						
						// my.alert({content:'建立延迟重连'})


						this.restSetTout = setTimeout(() => {
							// console.info('延迟重连')
							this.linkSocket()
						}, 50);
					}
				});



			}, 2500);

	},

  //处理socket发送回来的数据
  socketMsg(data){

		// console.info('socket======》////',data)

		data = JSON.parse(data)
		

		if(data.type == 111){
			clearTimeout(this.restSetTout)
			// console.info('取消掉重连')
			// my.alert({content:'取消掉重连'})

			return
		}

		// clearTimeout(this.startGameSet)
		


    console.info('这是socket发送回来的信息==》',data)

    // my.alert({titel:'socketMsg',content:JSON.stringify(data)})
    // my.showToast({titel:'socketMsg',content:JSON.stringify(data)})

		let openId='';
		
		if(data.type != 5){
			openId = data.data.openId;
		}

		// my.alert({content:data.type})



    if(data.type == 1 || data.type == 0){ //有人加入了房间

			// my.showToast({content:data.typeText})
    	// my.alert({titel:'socketMsg',content:JSON.stringify(data)})


			clearTimeout(this.addGameSet)
			clearTimeout(this.yaoqingSanShiMiao)

      setTimeout(() => {
				this.pipei.enemyInit({
					avatar:data.data.avatar,
					userNick:data.data.userNick,
					ranking:data.data.ranking,
					enemyOpenId:data.data.openId,
					isMember:data.data.isMember ? false : true
				})

				this.pipei.endPipei()

			}, 100);




      //*************************************************注意 */
      this.startGameSet = setTimeout(() => {

				//埋点
				getApp().BuriedPoint({actionText:"玩游戏",actionType:"playGame"})


        this.setData({
          showGame:'game',
          startGame:false,
          enemyData:{
            avatar:data.data.avatar,
						userNick:data.data.userNick,
						ranking:data.data.ranking,
						enemyOpenId:data.data.openId,
						isMember:data.data.isMember ? false : true
          },
          difficulty:data.data.levelInfo.difficulty== 1 ? "easily" : data.data.levelInfo.difficulty== 2 ? "medium" : "senior" ,
          activeIdx:data.data.levelInfo.difficulty== 1 ? 6 : data.data.levelInfo.difficulty== 2 ? 9 : 12 
				})

				this.gamePage.setImg(data.data.levelInfo.pictureUrl)
				this.gamePage.downTimeOp(data.data.levelInfo.gameTime)


				
      }, 3000);

    }else if(data.type == 3){   //后端结束了游戏，并返回游戏结果，以openid判断谁赢
			
			clearTimeout(this.startGameSet)
			
			this.cancelSet()

			this.setData({
				showGame:'main',
				startGame:false,
				showGame:false
			})

			if(this.gamePage){
      	this.gamePage.clearState()
			}


      setTimeout(() => {
				if(openId == getApp().openId){
					// my.alert({content:'你赢了'})

					this.checkGameSuccess('v')

				}else{
					// my.alert({content:'你输了'})

					this.checkGameSuccess('l')
				}


				this.changePage();
			}, 100);

			// getApp().cancelPiPei()



    }else if(data.type == 4){

			// getApp().cancelPiPei()

			this.cancelSet()


			clearTimeout(this.startGameSet)


			this.changePage();

			// my.alert({
			// 	title:'跑路',
			// 	content:data.type
			// })
			
			if(this.gamePage){
				this.gamePage.clearState()
			}
			
			// my.alert({content:openId})

      if(openId != getApp().openId){
				// my.alert({content:'对方离开房间，您赢了'})
				

				this.checkGameSuccess('v')

      }else{

				this.setData({
					startGame:false,
					showGame:'main'
				})
			
			}
    }else if(data.type == 5){  //后端终止游戏，超时都输了
			// my.alert({content:'游戏超时了，你输了'});


			clearTimeout(this.startGameSet)
			
			// getApp().cancelPiPei()

			this.cancelSet()

			this.changePage();
			
			this.checkGameSuccess('l')

			this.gamePage.clearState()
			
    }else if(data.type == 6){
			// my.showToast({
			// 	title:'对方给你发信息',
			// 	content:data.data
			// })

			if(this.gamePage && this.gamePage.msg){
				this.gamePage.msg(data.data)
			}

		}else{        //对方移动了拼图
			console.info('对方移动拼图===>',data)
			
			if(this.gamePage && this.gamePage.enemy){

				this.gamePage.enemy(data.data.picturePartDtoList)
				
			}

    }

  },
  
  //开始匹配
  startGame(){

		let that = this

    console.info('匹配游戏，进来了事件==>',this.data.startGame)

		if(this.data.startGame)return;
		

    this.setData({
      startGame:true,
		})


		// this.linkSocket();



		// getApp().cancelPiPei()
		// getApp().getOut()
		
		setTimeout(() => {
			this.setData({
				startGame:false
			})
		}, 300);

    getApp().cloud.application.httpRequest({
      
      'path' : '/api/c/game/startMatching', 
      'method':'POST',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
      'body':{
        difficulty:this.data.navBar[this.data.currentIndex].diff,
        type:1
      },
    
      'exts':{}  }).then(res => {
				
				console.info('===========================>',res)

      //判断是否是正常状态
      if(res.code != 200){
        
        if(res.code == -9999){
          
          this.setData({
            startGame:false,
            showGame:'main',
					})
					
          my.alert({content:"对不起，网络异常，请稍后重试"});

          return
				}
				
				
				
				if(res.code == -1342){
					that.setData({
						showGame:'main',
						startGame:false,
						roomId:'',
						isShowTip:true
					})

					return
				}

   
        return;
			}
			

			this.setData({
				roomId:res.data.gameLogId, //保存房间号
				showGame:'matching',             //直接开始匹配游戏页面
				startGame:false,            //开始游戏之后取消防抖装置的标识
			})

      

      

      // my.alert({title:'匹配结果',content:JSON.stringify(res)})

      console.info(res)
    })
  },
  
  //邀请好友
  invitationFriend(){

    if(this.data.startGame)return;

    this.setData({
      startGame:true
		})


		// getApp().cancelPiPei()
		// getApp().getOut()


		// this.linkSocket();
		
		setTimeout(() => {

			this.setData({
				startGame:false
			})

		}, 300);

    getApp().cloud.application.httpRequest({
      
      'path' : '/api/c/game/startMatching', 
      'method':'POST',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
      'body':{
        difficulty:this.data.navBar[this.data.currentIndex].diff,
        type:2
      },
    
      'exts':{}  }).then(res => {


			console.info('邀请好友返回的结果==>',res)
			


      if(res.code != 200){
				
				if(res.code == -1342){
					this.setData({
						showGame:'main',
						startGame:false,
						roomId:'',
						isShowTip:true
					})

					return
				}
        
        return;
      }

      // my.showLoading({
      //   content: '匹配中...'
			// });
			
			// my.alert({content:res.data.gameLogId})


      this.setData({
        roomId:res.data.gameLogId,
        startGame:false,
        showGame:'matching', 
        // isShowMatching:true
			})
			
			this.yaoqingSanShiMiao = setTimeout(() => {
				// console.info('好友没进来')
				
				this.setData({
					isShowTimeOut:true
				})

			}, 30000);
      
      setTimeout(() => {
        my.showSharePanel();
      }, 100);


    })
  },

  //加入对战
  addGame(id){

		this.setData({
			roomId:id
		})

		// this.linkSocket();

		getApp().cloud.application.httpRequest({
		
			'path' : '/api/c/game/intoGameWithInvitation', 
			'method':'POST',
			'headers':{ "Content-Type":"application/json"},
			'params':{},
			'body':{
				gameLogId:id
			},
		
			'exts':{}  }).then(res => {

				// my.alert({
				// 	content:JSON.stringify(res)
				// })


			if(res.code != 200){


				if(res.code == '-1342'){
					this.setData({
						showGame:'main',
						startGame:false,
						roomId:'',
						isShowTip:true
					})

					return
				}
				my.showToast({content:res.msg})
				
				return;
			}
			
			// my.alert({content:'加入对战'})

			this.setData({
				// showGame:'game',
				startGame:false,
				showGame:'matching', 
			})


			setTimeout(() => {
				this.pipei.endPipei()
			}, 10);

			// this.getEnemyInfo(id)

			

			console.info('加入对战结果=======》',res)


		})

    
	},
	
	//获取对手数据 ******************** 停用
	getEnemyInfo(id){
		getApp().cloud.application.httpRequest({
		
			'path' : '/api/c/game/getEnemyInfo', 
			'method':'POST',
			'headers':{ "Content-Type":"application/json"},
			'params':{},
			'body':{
				gameLogId:id
			},
		
			'exts':{}  }).then(res => {

				// my.alert({
				// 	content:JSON.stringify(res)
				// })


			if(res.code != 200){

				my.showToast({content:res.msg})

				this.setData({
					showGame:'main',
					startGame:false,
				})

				
				return;
			}
			
			// my.alert({content:'加入对战'})

			// console.info(res)

			this.pipei.enemyInit({
				avatar:res.data.avatar,
				userNick:res.data.userNick,
				ranking:res.data.ranking
			})

			this.addGameSet = setTimeout(() => {

				this.setData({
					showGame:'game',
					startGame:false,
          enemyData:{
            avatar:res.data.avatar,
						userNick:res.data.userNick,
						ranking:res.data.ranking
          },
					difficulty:res.data.gameLog.difficulty== 1 ? "easily" : res.data.gameLog.difficulty== 2 ? "medium" : "senior" ,
					activeIdx:res.data.gameLog.difficulty== 1 ? 6 : res.data.gameLog.difficulty== 2 ? 9 : 12 
				})

				this.gamePage.setImg(res.data.levelInfo.pictureUrl)

			}, 3000);
			

			console.info('获取对手信息=======》',res)


		})
	},

  //断开链接
  unLinkSocket(){

    my.onSocketOpen(() => {
      my.closeSocket()
    })

    my.onSocketClose((res) => {
      console.log('WebSocket 已关闭！')
    })
  },


  //游戏中 --组件-- 通讯
  gameMsg(o){

    console.info('主页面输出===>',o)

    let arr = [];

    o.data.map((v,i) => {
      if(v.disable){
        arr.push(v)
      }
    })

    

    this.sendMessage({
      currentPicturePartDto:{
                                "pictureIndex": o.idx+1,
                                "x": o.x,
                                "y": o.y 
                            },
      gameLogId: this.data.roomId,
      picturePartDtoList: arr

    })

  },

  //发讯息的接口通讯
  sendMessage(data){
    getApp().cloud.application.httpRequest({
      
      'path' : '/api/c/game/movePicture', 
      'method':'POST',
      'headers':{ "Content-Type":"application/json"},
      'params':{},
      'body':data,
    
      'exts':{}  }).then(res => {


      console.info('调用接口发信息==>',res)

      if(res.code != 200){

				my.showToast({title:'拼图',content:'网络异常'})
				
				this.setData({
					showGame:'main',
					startGame:false
				})
        
        return;
      }

    })
  },


  onLoad(query) {


    //获取皮肤
    this.setData({
      ...getApp().pifu.indexPage
    })
		

		this.getActivityInfo();

    let data = getApp().imgData;

    let mineData = {
			userNick:getApp().globalData.userInfo.nickName,
			avatar:getApp().globalData.userInfo.avatar
		}

    this.setData({
      imgData: data,
      mineData:mineData
    })

    //打开主页埋点
    getApp().BuriedPoint({actionText:"打开主页",actionType:"openHomePage "})

    //获取自定义分享信息
    this.getShare();

    //大奖
    this.getBigPrize();

    //获取店铺信息
    this.getShopId();

    //规则
    this.getRules();

    //刷新
    this.changePage()
    
    //今日完成任务状态
		this.getTodayTaskStatus();
		
		if(query.addRoomId && query.addRoomId != 'biaoji'){

			// my.alert({
			// 	content:query.addRoomId
			// })
			
			setTimeout(() => {
				this.addGame(query.addRoomId);
			}, 800);

			// this.flagSet = set(() => {
			// 	if(getApp().flagAddRoom){
			// 		clearInterval(this.flagSet)
			// 		this.addGame(query.addRoomId);
			// 	}
			// }, 200);
			
			// getApp().httpRequest(res=>{
			// 	my.alert({content:"add game"});
			// 	this.addGame(query.addRoomId);
			// })


			this.setData({
				roomId:query.addRoomId
			})

			return;

		}
    

		if(query.openId && query.openId != getApp().openId){

			// my.alert({
			// 	title:'openId',
			// 	content:query.openId
			// })

			getApp().cloud.application.httpRequest({
				'path' : '/api/c/task/share', 
				'method':'POST',
				'headers':{ "Content-Type":"application/json"},
				'params':{},
				'body':{
					openId:query.openId
				},
				'exts':{}  }).then(res => {

				console.log("分享",res);

				// my.alert({
				// 	title:'返回结果',
				// 	content:JSON.stringify(res)
				// })

				//判断是否是正常状态
				if(res.code != 200){
					// my.alert({
					// 	content:res.msg
					// }) 
				}else{
					
					

				}
			})
		}

  },

  // 页面刷新
  changePage(){

    //获取抽奖次数
    this.getGameNum();

    //排行榜数据
    this.getList();

    //获取当前用户排名
    this.getUserInfo();

    //获取我的奖品信息
    this.getPrize();

    //获取排行榜第一名
    this.geiNumberOne();

    //获取收藏商品组
    this.getCollection();

    //获取用户今日任务状态
		this.getTodayTaskStatus();
		
		if(this.data.isShowTask){
			setTimeout(() => {
					this.showTask();
			}, 200);
		}

  },

  onReady() {
    
	},
	
	getTaskData(){
		plugin.getTaskList()
    .then(res => {
      let taskData = res || []
      console.log('任务插件=============》', taskData)
    }).catch(err => {
      console.log('任务插件=============》', err)
    })
	},

  onShow() {

		// this.getTaskData()

		clearInterval(this.restSocketSet)

		clearInterval(this.setTTT)

		this.linkSocket();

    this.resetLinkSocket();

		this.changePage();


		setTimeout(() => {
			this.changePage()
		}, 4000);

		// this.setTTT = setInterval(() => {

		// 	if(this.data.showGame == 'matching'){
		// 		this.linkSocket();
		// 	}
			
    // },800)
    
    let this_ = this

    //this.openMember();

    memberPlugin.checkMember({
      
      //sellerId为可选参数，不填则为当前小程序Owner用户ID

      sellerId:2838892713,

      success(v) {
        
        if( v.data.isMember == true || v.data.isMember == 'true' ){
          this_.joinVip();
        }

      },
      fail(v) {
        // my.alert({
        //   title: "会员检查失败",
        //   content: JSON.stringify(v),
        // })          
      } 

    });

    
  },
  onHide() {
		clearInterval(this.setTTT)
		clearInterval(this.restSocketSet)
  },
  onUnload() {
		this.unLinkSocket();
		
		clearInterval(this.setTTT)

		clearInterval(this.restSocketSet)

    getApp().cancelPiPei();
    getApp().getOut();
    
  },
  onTitleClick() {
    // 标题被点击
  },
  onPullDownRefresh() {
    // 页面被下拉
  },
  onReachBottom() {
    // 页面被拉到底部
  },

  onShareAppMessage() {
    return {
      title: this.data.shareData.title,
      desc: this.data.shareData.content,
      imageUrl: this.data.shareData.logo,
      path:`pages/load/load?addRoomId=${this.data.roomId}&openId=${getApp().openId}`
    };  
  }, 
});
